<template>
  <div class="dashboard-page">
    <el-page-header title="返回" content="数据总览" class="page-header" />
    
    <div class="dashboard-content">
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card class="stat-card primary-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><CreditCard /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">今日银行流水</div>
                <div class="stat-value">{{ dashboardStats.bankData.today }}</div>
                <div class="stat-trend">
                  <el-icon class="trend-up"><Top /></el-icon>
                  <span class="trend-text">{{ dashboardStats.bankData.trend }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card success-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">今日订单</div>
                <div class="stat-value">{{ dashboardStats.orderData.today }}</div>
                <div class="stat-trend">
                  <el-icon class="trend-up"><Top /></el-icon>
                  <span class="trend-text">{{ dashboardStats.orderData.trend }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card warning-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Notification /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">今日发票</div>
                <div class="stat-value">{{ dashboardStats.invoiceData.today }}</div>
                <div class="stat-trend">
                  <el-icon class="trend-down"><Bottom /></el-icon>
                  <span class="trend-text">{{ dashboardStats.invoiceData.trend }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card total-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-title">数据总量</div>
                <div class="stat-value">{{ dashboardStats.total.total }}</div>
                <div class="stat-trend">
                  <el-icon class="trend-up"><Top /></el-icon>
                  <span class="trend-text">{{ dashboardStats.total.trend }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" class="charts-row">
        <el-col :span="16">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>数据源状态</span>
              </div>
            </template>
            <div class="data-source-container">
              <el-row :gutter="15">
                <el-col :span="8" v-for="(source, key) in dataSourceStatus" :key="key" class="source-col">
                  <el-card 
                    class="source-card" 
                    :class="{
                      'enabled': source.enabled, 
                      'disabled': !source.enabled,
                      'status-success': source.status === 'success',
                      'status-warning': source.status === 'warning',
                      'status-error': source.status === 'error'
                    }"
                    @click="showSourceDetails(key)"
                  >
                    <div class="source-content">
                      <div class="source-icon">
                        <el-icon v-if="key === 'bank'"><CreditCard /></el-icon>
                        <el-icon v-else-if="key === 'salesOrder'"><ShoppingBag /></el-icon>
                        <el-icon v-else-if="key === 'purchaseOrder'"><ShoppingCart /></el-icon>
                        <el-icon v-else-if="key === 'incomingInvoice' || key === 'outgoingInvoice'"><Document /></el-icon>
                        <el-icon v-else-if="key === 'announcement'"><Bell /></el-icon>
                        <el-icon v-else><Files /></el-icon>
                      </div>
                      <div class="source-info">
                        <div class="source-name">{{ source.name }}</div>
                        <div class="source-status">
                          <el-tag 
                            :type="source.status === 'success' ? 'success' : 
                                   source.status === 'warning' ? 'warning' : 
                                   source.status === 'error' ? 'danger' : 'info'"
                            size="small"
                          >
                            <el-icon v-if="source.status === 'success'"><Check /></el-icon>
                            <el-icon v-else-if="source.status === 'warning'"><Warning /></el-icon>
                            <el-icon v-else-if="source.status === 'error'"><Close /></el-icon>
                            <el-icon v-else><Minus /></el-icon>
                            {{ source.status === 'success' ? '成功' : 
                               source.status === 'warning' ? '部分成功' : 
                               source.status === 'error' ? '失败' : '未同步' }}
                          </el-tag>
                        </div>
                        <div class="source-stats">
                          上传: {{ source.uploadCount }} | 成功: {{ source.successCount }}
                        </div>
                        <div class="source-time">
                          最后同步: {{ source.lastSync }}
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="recent-card">
            <template #header>
              <div class="card-header">
                <span>最近同步记录</span>
              </div>
            </template>
            <div class="recent-list">
              <el-timeline>
                <el-timeline-item
                  v-for="(record, index) in syncHistory"
                  :key="index"
                  :timestamp="record.timestamp"
                  placement="top"
                >
                  <el-card class="activity-card" :class="{'success': record.success}">
                    <div class="record-header">
                      <span class="record-type">{{ record.type }}</span>
                      <el-tag :type="record.success ? 'success' : 'danger'" size="small">
                        {{ record.success ? '成功' : '失败' }}
                      </el-tag>
                    </div>
                    <p class="record-message">{{ record.message }}</p>
                    <p class="record-count">数据条数: {{ record.count }}</p>
                  </el-card>
                </el-timeline-item>
                <el-timeline-item v-if="syncHistory.length === 0">
                  <el-card class="activity-card">
                    <p>暂无同步记录</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
            <div class="card-footer">
              <el-button type="primary" @click="openSaasPortal" plain>
                在SaaS端查看详情
                <el-icon class="el-icon--right"><ArrowRight /></el-icon>
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 数据源详情对话框 -->
    <el-dialog
      v-model="sourceDetailVisible"
      :title="currentSource?.name"
      width="600px"
    >
      <div class="source-detail-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="数据源名称">{{ currentSource?.name }}</el-descriptions-item>
          <el-descriptions-item label="启用状态">
            <el-tag :type="currentSource?.enabled ? 'success' : 'danger'">
              {{ currentSource?.enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后同步时间">{{ currentSource?.lastSync }}</el-descriptions-item>
          <el-descriptions-item label="上传数据条数">{{ currentSource?.uploadCount }}</el-descriptions-item>
          <el-descriptions-item label="成功处理条数">{{ currentSource?.successCount }}</el-descriptions-item>
          <el-descriptions-item label="失败条数">{{ currentSource?.uploadCount - currentSource?.successCount }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="sync-history-section">
          <h4>最近同步记录</h4>
          <el-table :data="currentSourceHistory" style="width: 100%" size="small">
            <el-table-column prop="timestamp" label="时间" width="150" />
            <el-table-column prop="message" label="状态" />
            <el-table-column prop="count" label="条数" width="80" />
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="sourceDetailVisible = false">关闭</el-button>
          <el-button type="primary" @click="openSaasPortal">在SaaS端查看详情</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { 
  CreditCard, 
  Document, 
  Notification, 
  DataAnalysis,
  Top,
  Bottom,
  ArrowDown,
  ShoppingBag,
  ShoppingCart,
  Bell,
  Files,
  Check,
  Warning,
  Close,
  Minus,
  ArrowRight
} from '@element-plus/icons-vue'
import { useDashboardData } from '../composables/useDashboardData'

const { 
  dashboardStats, 
  dataSourceStatus, 
  syncHistory, 
  fetchDashboardData, 
  initDashboardData 
} = useDashboardData()

// 数据源详情对话框
const sourceDetailVisible = ref(false)
const currentSourceKey = ref('')
const currentSource = computed(() => dataSourceStatus[currentSourceKey.value] || null)
const currentSourceHistory = ref([])

// 定时器ID
let intervalId = null

// 显示数据源详情
const showSourceDetails = (key) => {
  currentSourceKey.value = key
  // 这里应该获取该数据源的详细历史记录
  currentSourceHistory.value = syncHistory.value.filter(record => 
    record.type === dataSourceStatus[key].name
  )
  sourceDetailVisible.value = true
}

// 打开SaaS门户
const openSaasPortal = () => {
  // 在实际应用中，这里应该打开对应的SaaS端页面
  window.open('http://localhost:4000', '_blank')
}

// 组件挂载时初始化数据
onMounted(() => {
  fetchDashboardData()
  intervalId = initDashboardData()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId)
  }
})
</script>

<style scoped>
.dashboard-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.dashboard-content {
  background: #f0f2f5;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  transition: all 0.3s;
  height: 120px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
  height: 100%;
}

.stat-icon {
  font-size: 36px;
  padding: 15px;
  border-radius: 10px;
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
}

.trend-up {
  color: #52c41a;
}

.trend-down {
  color: #ff4d4f;
}

.trend-text {
  color: #666;
}

.primary-card .stat-icon {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

.primary-card .stat-value {
  color: #667eea;
}

.success-card .stat-icon {
  background: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.success-card .stat-value {
  color: #52c41a;
}

.warning-card .stat-icon {
  background: rgba(250, 173, 20, 0.1);
  color: #faad14;
}

.warning-card .stat-value {
  color: #faad14;
}

.total-card .stat-icon {
  background: rgba(118, 75, 162, 0.1);
  color: #764ba2;
}

.total-card .stat-value {
  color: #764ba2;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card, .recent-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.period-button {
  font-size: 12px;
}

.data-source-container {
  padding: 10px 0;
}

.source-col {
  margin-bottom: 15px;
}

.source-card {
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #ebeef5;
}

.source-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.source-card.enabled {
  background-color: #f0f9eb;
}

.source-card.disabled {
  background-color: #f5f5f5;
  opacity: 0.6;
}

.source-card.status-success {
  border-left: 4px solid #67c23a;
}

.source-card.status-warning {
  border-left: 4px solid #e6a23c;
}

.source-card.status-error {
  border-left: 4px solid #f56c6c;
}

.source-content {
  display: flex;
  gap: 15px;
  align-items: center;
}

.source-icon {
  font-size: 24px;
  color: #909399;
}

.source-info {
  flex: 1;
}

.source-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.source-status {
  margin-bottom: 5px;
}

.source-stats {
  font-size: 12px;
  color: #666;
  margin-bottom: 3px;
}

.source-time {
  font-size: 12px;
  color: #999;
}

.recent-list {
  max-height: 350px;
  overflow-y: auto;
}

.activity-card {
  margin-top: 10px;
  border: 1px solid #e4e7ed;
}

.activity-card.success {
  border-left: 4px solid #67c23a;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.record-type {
  font-weight: 500;
}

.record-message {
  margin: 5px 0;
  font-size: 12px;
  color: #666;
}

.record-count {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.card-footer {
  margin-top: 15px;
  text-align: center;
}

.source-detail-content {
  padding: 10px 0;
}

.sync-history-section {
  margin-top: 20px;
}

.sync-history-section h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #333;
}
</style>